package com.zgkxzx.mvvmbase.api;


import android.util.Log;


import com.zgkxzx.mvvmbase.BaseApplication;
import com.zgkxzx.mvvmbase.utils.NetWorkUtil;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/9/9.
 */
public class ApiManager {
    private final static String TAG = ApiManager.class.getSimpleName();

    private final static int CACHE_SIZE = 10 * 1024 * 1024; // 10 MiB
    //private final static String PICTURE_BASE_URL = "http://gank.io/api/";
    private final static String PICTURE_BASE_URL = "https://leancloud.cn:443/";

    public static ApiManager apiManager;

    // 缓存地址：/data/data/com.zgkxzx.inheart/cache/InHeartCache
    private File httpCacheDirectory = new File(BaseApplication.getContext().getCacheDir(), "InHeartCache");

    private Cache cache = new Cache(httpCacheDirectory, CACHE_SIZE);

    //缓存拦截
    private Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            if (NetWorkUtil.isNetWorkAvailable(BaseApplication.getContext())) {
                int maxAge = 60; // 在线缓存在1分钟内可读取
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // 离线时缓存保存4周
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
        }
    };

    //日志拦截
    private class LogInterceptor implements Interceptor {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.v(TAG, "request:" + request.toString());
            long t1 = System.nanoTime();
            okhttp3.Response response = chain.proceed(chain.request());
            long t2 = System.nanoTime();
            Log.v(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            okhttp3.MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            Log.i(TAG, "response body:" + content);
            return response.newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-LC-Id", "CMUPHuy90722Fibjdtd3y6wy-gzGzoHsz")
                    .addHeader("X-LC-Key", "AMcaGTCVdB8PFGReHtCIu2b9")
                    .body(okhttp3.ResponseBody.create(mediaType, content))
                    .build();
        }

    }

    private class SignInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-LC-Id", "CMUPHuy90722Fibjdtd3y6wy-gzGzoHsz")
                    .addHeader("X-LC-Key", "AMcaGTCVdB8PFGReHtCIu2b9")
                    .build();
            return chain.proceed(request);
        }

    }

    //OkHttpClient 初始化
    private OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
            .addInterceptor(new SignInterceptor())
            .addInterceptor(new LogInterceptor())
            .cache(cache)
            .build();

    public static ApiManager getInstance() {
        if (apiManager == null) {
            synchronized (ApiManager.class) {
                if (apiManager == null) {
                    apiManager = new ApiManager();
                }
            }
        }
        return apiManager;
    }

    public Retrofit initRetrofit() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(PICTURE_BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }
}



